package com.franklin.ideaplugin.api.ui.editor;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import com.franklin.ideaplugin.api.icon.ApiIcons;
import com.franklin.ideaplugin.api.ui.IBaseComponent;

import javax.swing.*;

/**
 * @author Ye Junhui
 * @since 2023/7/12
 */
public interface IBaseFormatJsonEditor extends IBaseComponent {

    /**
     * 初始化Format按钮
     * @param customEditor
     * @param formatBtn
     */
    default void initFormatButton(CustomEditor customEditor, JButton formatBtn){
        formatBtn.setIcon(ApiIcons.PRETTY_PRINT_ICON);
        formatBtn.setText("Format the text content to pretty json");
        formatBtn.setToolTipText("Format the text content to pretty json");
        formatBtn.addActionListener(e -> {
            String text = customEditor.getText();
            try {
                JSONObject jsonObject = JSON.parseObject(text);
                String pretty = jsonObject.toJSONString(JSONWriter.Feature.PrettyFormat);
                customEditor.setText(pretty,CustomEditor.JSON_FILE_TYPE);
            } catch (Exception exception) {
                try {
                    JSONArray jsonArray = JSON.parseArray(text);
                    String pretty = jsonArray.toJSONString(JSONWriter.Feature.PrettyFormat);
                    customEditor.setText(pretty,CustomEditor.JSON_FILE_TYPE);
                } catch (Exception ex) {

                }
            }
        });
    }
}
